import sys

from PySide2 import QtCore
import requests, bs4
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from home3_scroll import *
from playlist_show import *
import requests
import json
from PySide2.QtMultimedia import *
import pcamcapture as p
import time

import cv2
import numpy as np
from queue import Queue




#home
class MyClass(QWidget,Ui_Form):
    signal_1=QtCore.Signal(str,str,QImage)
    clocktime=QtCore.Signal(str)
    musicprogress1=QtCore.Signal(str,int,str)

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setupUi(self)

        # *记录鼠标位置 self.setMouseTracking(False)
        self.last_time_move = 0
        
        #去除边框
        #self.setWindowFlag(Qt.FramelessWindowHint)
        #self.setAttribute(Qt.WA_TranslucentBackground)

        '''打开新窗口的命令'''
        self.form2=playlistClass()
        #获得歌曲信息
        self.signal_1.connect(self.form2.get_data)
        #获得时间信息（实现每秒更新问题）
        self.clocktime.connect(self.form2.set_time)
        #获得播放进度
        self.musicprogress1.connect(self.form2.set_progress)

        self.quanping.clicked.connect(self.showplaylist)

        #设置时钟
        self.timer=QTimer()
        self.timer.start()
        self.timer.timeout.connect(self.showtime)
        
        #设置播放媒体
        self.playing=False
        self.player=QMediaPlayer(self)

        # #设置时钟监视音乐播放状态【9】
        # self.timer = QTimer(self)
        # #self.timer.setInterval(1000)
        # self.timer.start(500)
        # self.timer.timeout.connect(self.check_music_status)

        #播放与暂停【1】
        self.n=1
        self.bofang.clicked[bool].connect(self.iconchange1)

        #切歌按键
        self.xiayishouge.clicked.connect(self.musicget)
        self.shangyishouge.clicked.connect(self.musicget)

        #设置展开播放列表的按钮【2】
        

        #进度条设置,音乐状态监听【10】
        self.process_timer =QTimer()
        self.process_timer.start(1000)
        self.process_timer.timeout.connect(self.process_timer_status)


        

        # '''手势识别的线程'''
        # self.thread_1 = Worker()
        # self.thread_1.gesturePose.connect(self.getpose)
        # self.thread_1.start()
        '''动态手势的识别线程'''
        self.thread_2 = Worker1()
        self.thread_2.movePose.connect(self.panduan)
        self.thread_2.start()


        self.show()


    #【4】鼠标行为记录
    def eventFilter(self, source, event):
        if event.type() == QEvent.MouseMove:
            #print(event.pos().x())
            if self.last_time_move == 0:
                self.last_time_move = event.pos().x()

            distance = self.last_time_move - event.pos().x()
            self.scroll_bar.setValue(self.scroll_bar.value() + distance)
            self.last_time_move = event.pos().x()

        elif event.type() == QEvent.MouseButtonRelease:
            self.last_time_move = 0
        return QWidget.eventFilter(self, source, event)

    #【1】播放切换
    def iconchange1(self):
        self.n+=1
        if self.n>2:
            self.n=1
        self.icon2.addFile(u"xiangmu1/pics/bofang_"+str(self.n), QSize(), QIcon.Normal, QIcon.Off)
        self.bofang.setIcon(self.icon2)
        
        if self.n==1:
            self.player.play()
            self.process_timer.start()#设置计时器暂停与继续
        elif self.n==2:
            self.player.pause()
            self.process_timer.stop()

    #【2】展开播放列表
    def showplaylist(self):
        self.form2.show()
        self.form2.signal_2.connect(self.musicget)#★信息的发送不分顺序但一定要在界面2show后，保证信号是从show出来的界面2发出来的★
            
    #【3】显示时间
    def showtime(self):
        datetime=QDateTime.currentDateTime()
        self.text1=datetime.toString('HH:mm:ss')
        self.clock.setText(self.text1)
        self.clocktime.emit(self.text1)
        
    #【5】音乐API
    def musicget(self):
        url='https://api.66mz8.com/api/rand.music.163.php?format=json'
        res=requests.get(url)
        dict=res.json()

        #处理图片
        # print(dict)
        # print('------------------------')
        url2=dict['music_pic']
        res2=requests.get('http://p1.music.126.net/8dzD62VK8jLDbhEqkmpIAg==/18277181788626198.jpg')
        self.img=QImage.fromData(res2.content)

        #设置歌曲名字
        self.name='Faded'
        self.musicname.setText(dict['name'])

        #设置歌手名字
        self.artist='Alan Walker'
        self.musicsinger.setText(self.artist)


        #设置专辑封面图片
        self.albumpics.setPixmap(QPixmap(self.img))

        #设置进度条开始数值
        self.process_value=0
        self.time=0

        #处理歌曲
        url3='http://music.163.com/song/media/outer/url?id=36990266.mp3'
        content=QMediaContent(QtCore.QUrl(url3))
        self.player.setMedia(content)
        self.player.setVolume(30)
        self.player.play()
        #print('--------------------------')

        #切换图标为播放
        self.icon2.addFile(u"xiangmu1/pics/bofang_1.png", QSize(), QIcon.Normal, QIcon.Off)
        self.bofang.setIcon(self.icon2)

        self.signal_1.emit(self.artist,self.name,self.img)

    #【10】设置时间,进度
    def process_timer_status(self):
        self.player_status = self.player.mediaStatus()
        player_duration = self.player.duration()
        #print("音乐时间：",player_duration)
        #print("当前播放器状态",self.player_status)
        #print('播放进度：'+str(self.player.position()))
        if self.player_status == 7:  #QtCore.Qt中的对应，播放完成自动切换下一首歌
            self.musicget()
            
        if player_duration > 0:#总时间的显示
            y=list(str(player_duration))
            self.x=y[0]+y[1]+y[2]
            timemin=int(self.x)//60
            times=int(self.x)%60
            self.duration1 = str(timemin).zfill(2)+':'+str(times).zfill(2)
                        
            # number1=player_duration//6000
            # number2=player_duration%60
            self.songtime.setText(str(self.duration1))

        time=self.player.position()//1000#获取倒数第四位开始的数值
        timecount1=int(time)//60
        timecount2=int(time)%60
        self.duration = str(timecount1).zfill(2)+':'+str(timecount2).zfill(2)
        self.songtiming.setText(self.duration)
        

        #数值设置与时钟刷新时间对应起来
        #self.process_value=timecount2/int(self.x)*100
        self.process_value =self.process_value + 100/(int(self.x))
        #print("当前进度：",self.process_value)
        # print(self.x)
        # print(timecount2)
        # print(round(self.process_value))
        self.musicprogress.setValue(self.process_value)
        self.musicprogress.update()
        self.musicprogress1.emit(self.duration,self.process_value,self.duration1)

    #【11】手势识别子线程信息处理
    def getpose(self,ge):
        # print(ge)
        if ge=='Two':
            self.musicget()
        elif ge=='Five':
            self.iconchange1()
        elif ge=='Ok':
            self.showplaylist()

    def panduan(self,pose):
        print('动作',pose)
        #翻页动画
        animation = QPropertyAnimation(self.scroll_area)
        animation.setTargetObject(self.scroll_contents)
        animation.setPropertyName(b'pos')

        #设置开始属性值
        x=0
        y=0
        #动画的相对挪动位置
        animation.setStartValue(QPoint(x,y))
        if pose == 'right':
            if x<0 :
                x=x+700
                animation.setEndValue(QPoint(x,y))
                animation.setDuration(2000)
                animation.start()
                #self.scroll_bar.setValue(self.scroll_bar.value()+100)
            elif x>=0:
                pass
        elif pose == 'left':
            x=x-700
            animation.setEndValue(QPoint(-700,0))
            #self.scroll_bar.setValue(100)
            animation.setDuration(500)
            animation.start()



# '''手势识别子线程'''
# class Worker(QThread):

#     gesturePose = QtCore.Signal(str)  #更新进度条

#     def __init__(self):
#         super(Worker, self).__init__()

#     def run(self):
#         while True:
#             gesture3=p.camcapture()
#             #print(gesture3)
#             #print('------')
#             self.gesturePose.emit(gesture3)
#             time.sleep(1)

'''动态翻页手势线程'''
class Worker1(QThread):
    movePose = QtCore.Signal(str)

    def __init__(self):
        super(Worker1,self).__init__()

    def run(self):
        cap_region_x_begin=0.5  # start point/total width
        cap_region_y_end=0.8  # start point/total width
        bgSubThreshold = 50
        learningRate = 0
        
        # 去除背景
        # def removeBG(frame):
        #     fgmask = bgModel.apply(frame,learningRate=learningRate)
        #     # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
        #     # res = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
        
        #     kernel = np.ones((3, 3), np.uint8)
        #     fgmask = cv2.erode(fgmask, kernel, iterations=1)
        #     res = cv2.bitwise_and(frame, frame, mask=fgmask)
        #     return res
        
        
        #获取摄像头
        camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
        width = int(camera.get(3))
        height = int(camera.get(4))
        
        firstFrame = None
        lastDec = None
        firstThresh = None
        
        feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7)
        
        # Parameters for lucas kanade optical flow
        lk_params = dict(winSize=(15, 15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
        
        color = np.random.randint(0, 255, (100, 3))
        num = 0
        
        q_x = Queue(maxsize=10)
        q_y = Queue(maxsize=10)
        number=-1
        list1=[None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None]
        while camera.isOpened():
            grabbed, frame = camera.read()
            # print(grabbed)
        
            frame = cv2.bilateralFilter(frame, 5, 50, 100)  # smoothing filter
            frame = cv2.flip(frame, 1)  # 水平翻转图像
            # cv2.rectangle(frame, (int(cap_region_x_begin * frame.shape[1]), 0),
            #              (frame.shape[1], int(cap_region_y_end * frame.shape[0])), (255, 0, 0), 2)
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            gray = cv2.GaussianBlur(gray, (21, 21), 0)
        
            if firstFrame is None:
                firstFrame = gray
                continue
        
            frameDelta = cv2.absdiff(firstFrame, gray)
            thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
            # 下面的是几种不同的二值化的方法，感觉对我来说效果都差不多
            # thresh = cv2.adaptiveThreshold(frameDelta,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            # cv2.THRESH_BINARY,11,2)
            # thresh = cv2.adaptiveThreshold(frameDelta,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            #           cv2.THRESH_BINARY,11,2)
            thresh = cv2.dilate(thresh, None, iterations=2)
            p0 = cv2.goodFeaturesToTrack(thresh, mask=None, **feature_params)
            if p0 is not None:
                x_sum = 0
                y_sum = 0
                for i, old in enumerate(p0):
                    x, y = old.ravel()
                    x_sum += x
                    y_sum += y
                x_avg = x_sum / len(p0)
                y_avg = y_sum / len(p0)
        
                if q_x.full():
                    # print(list(q_x.queue))
                    qx_list = list(q_x.queue)
                    key = 0
                    diffx_sum = 0
                    for item_x in qx_list:
                        key += 1
                        if key < 10:
                            diff_x = item_x - qx_list[key]
                            diffx_sum += diff_x
                            # print diff_x
                    if diffx_sum < 0:# and x_avg < 500:
                        number=number+1
                        #print( "To right",number)
                        list1[number]='right'
                        cv2.putText(frame, "To right", (100, 100), 0, 0.5, (0, 0, 255), 2)
                        if number==24:
                            maxlabel = max(list1,key=list1.count)
                            self.movePose.emit(maxlabel)
                            #print(maxlabel)
                            number=0
                    else:
                        number=number+1
                        #print( "To left",number)
                        list1[number]='left'
                        cv2.putText(frame, "To left", (100, 100), 0, 0.5, (0, 0, 255), 2)
                        if number==24:
                            maxlabel = max(list1,key=list1.count)
                            #print(maxlabel)
                            self.movePose.emit(maxlabel)
                            number=0
                        pass
            

        
                    # print(x_avg)
                    q_x.get()
                q_x.put(x_avg)
                cv2.putText(frame, str(x_avg), (300, 100), 0, 0.5, (0, 0, 255), 2)
                frame = cv2.circle(frame, (int(x_avg), int(y_avg)), 5, color[i].tolist(), -1)
            else:
                number=number+1
                #print('静止',)
                list1[number]=''
                if number==24:
                    maxlabel = max(list1,key=list1.count)
                    self.movePose.emit(maxlabel)
                    #print(maxlabel)
                    number=0


            #cv2.imshow("Camera", frame)
            cv2.waitKey(10)
            firstFrame = gray.copy()


        

if __name__=='__main__':
    app=QApplication(sys.argv)
    mc=MyClass()
    app.exec_()